<?php

namespace App\Admin\Middleware;

use App\Models\Application;
use Closure;
use Dcat\Admin\Admin;
use Exception;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class SetApplication
{
    /**
     * @throws Exception
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = Admin::user();
        if ($user) {
            $application = Application::ofEnabled()
                ->where('admin_id', Admin::user()->getKey())
                ->where('expired_at', '>', now())
                ->first();

            if (!$application && !$user->isAdministrator()) {
                throw new Exception('未绑定应用，暂时无法操作');
            }

            $request->merge(['application' => $application]);
        }

        return $next($request);
    }
}
